<template>
  <div class="client-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button 
        @click="goBack" 
        :icon="ArrowLeft" 
        circle 
        size="small"
        class="back-btn"
      />
      <h2 class="page-title">编辑客户信息</h2>
      <div class="header-placeholder"></div>
    </div>

    <!-- 客户基础信息展示 -->
    <div class="client-info-card">
      <div class="card-header">
        <div class="client-avatar">
          <el-icon size="32"><User /></el-icon>
        </div>
        <div class="client-basic">
          <h3>{{ clientInfo?.clientCode }}</h3>
          <p class="client-type-info">
            <el-tag size="small">{{ clientInfo?.marketType }}</el-tag>
          </p>
        </div>
      </div>
      <div class="readonly-info">
        <div class="info-item">
          <span class="label">客户代码：</span>
          <span class="value">{{ clientInfo?.clientCode }}</span>
        </div>
      </div>
    </div>

    <!-- 可编辑表单 -->
    <div class="edit-form-card">
      <div class="card-title">
        <el-icon class="title-icon"><Edit /></el-icon>
        可编辑信息
      </div>
      
      <el-form 
        :model="editForm" 
        :rules="formRules"
        ref="editFormRef"
        label-position="top"
      >
        <el-form-item label="客户名称" prop="clientName">
          <el-input
            v-model="editForm.clientName"
            placeholder="请输入客户名称"
            clearable
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="市场类型" prop="marketType">
          <el-select 
            v-model="editForm.marketType" 
            placeholder="请选择市场类型"
            style="width: 100%"
          >
            <el-option 
              v-for="type in marketTypes" 
              :key="type.value"
              :label="type.label" 
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="终端类型" prop="terminalType">
          <el-select 
            v-model="editForm.terminalType" 
            placeholder="请选择终端类型"
            style="width: 100%"
          >
            <el-option 
              v-for="type in terminalTypes" 
              :key="type.value"
              :label="type.label" 
              :value="type.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 修改说明 -->
    <div class="info-notice">
      <el-alert
        title="修改说明"
        type="info"
        :closable="false"
        show-icon
      >
        <ul>
          <li>您只能修改您负责的客户信息</li>
          <li>客户代码不可修改</li>
          <li>修改后的信息将立即生效</li>
        </ul>
      </el-alert>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        size="large" 
        @click="goBack"
        :disabled="submitting"
      >
        取消
      </el-button>
      <el-button 
        type="primary" 
        size="large"
        @click="submitForm"
        :loading="submitting"
        :disabled="!hasChanges"
      >
        保存修改
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { 
  ArrowLeft, 
  User, 
  Edit
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const clientInfo = ref(null)
const editFormRef = ref<FormInstance>()

// 表单数据
const editForm = reactive({
  clientName: '',
  marketType: '',
  terminalType: ''
})

// 原始数据（用于对比是否有变更）
const originalData = ref({
  clientName: '',
  marketType: '',
  terminalType: ''
})

// 市场类型选项
const marketTypes = [
  { label: '城网', value: '城网' },
  { label: '农网', value: '农网' }
]

// 终端类型选项
const terminalTypes = [
  { label: '普通终端', value: '普通终端' },
  { label: '一般现代终端', value: '一般现代终端' },
  { label: '加盟终端', value: '加盟终端' },
  { label: '直营终端', value: '直营终端' }
]

// 表单验证规则
const formRules: FormRules = {
  clientName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 1, max: 100, message: '客户名称长度在1到100个字符', trigger: 'blur' }
  ],
  marketType: [
    { required: true, message: '请选择市场类型', trigger: 'change' }
  ],
  terminalType: [
    { required: true, message: '请选择终端类型', trigger: 'change' }
  ]
}

// 计算属性
const hasChanges = computed(() => {
  return editForm.clientName !== originalData.value.clientName ||
         editForm.marketType !== originalData.value.marketType ||
         editForm.terminalType !== originalData.value.terminalType
})

// 方法
const goBack = () => {
  if (hasChanges.value) {
    ElMessageBox.confirm(
      '您有未保存的修改，确定要离开吗？',
      '确认离开',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      router.back()
    }).catch(() => {
      // 用户取消
    })
  } else {
    router.back()
  }
}

const loadClientInfo = async () => {
  try {
    loading.value = true
    const clientId = parseInt(route.params.clientId as string)
    
    if (!clientId || isNaN(clientId)) {
      ElMessage.error('客户ID无效')
      router.back()
      return
    }

    // 获取客户详情
    const result = await trpc.client.get.query({ id: clientId })
    
    if (result.success) {
      clientInfo.value = result.data
      
      // 检查当前用户是否有权限编辑此客户
      if (!checkEditPermission(result.data)) {
        return // 如果没有权限，函数内部已经处理跳转
      }
      
      // 初始化表单数据
      editForm.clientName = result.data.clientName
      editForm.marketType = result.data.marketType
      editForm.terminalType = result.data.terminalType
      
      // 保存原始数据
      originalData.value = {
        clientName: result.data.clientName,
        marketType: result.data.marketType,
        terminalType: result.data.terminalType
      }
    } else {
      ElMessage.error('获取客户信息失败')
      router.back()
    }
  } catch (error) {
    console.error('加载客户信息失败:', error)
    ElMessage.error('加载客户信息失败')
    router.back()
  } finally {
    loading.value = false
  }
}

const checkEditPermission = (clientData: any) => {
  const managerId = getCurrentManagerId()
  if (!managerId) {
    ElMessage.error('请先登录')
    router.push('/login')
    return false
  }

  // 检查客户的经理分配中是否包含当前经理
  const managerAssignments = clientData.managerAssignments || []
  const hasPermission = managerAssignments.some(
    (assignment: any) => assignment.managerId === managerId
  )
  
  if (!hasPermission) {
    ElMessage.error('您没有权限编辑此客户信息')
    router.back()
    return false
  }
  
  return true
}

const submitForm = async () => {
  if (!editFormRef.value) return
  
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    submitting.value = true
    const managerId = getCurrentManagerId()
    const clientId = parseInt(route.params.clientId as string)
    
    if (!managerId) {
      ElMessage.error('请先登录')
      return
    }

    // 准备更新数据（只包含有变化的字段）
    const updateData: any = {
      managerId,
      clientId
    }
    
    if (editForm.clientName !== originalData.value.clientName) {
      updateData.clientName = editForm.clientName
    }
    
    if (editForm.marketType !== originalData.value.marketType) {
      updateData.marketType = editForm.marketType
    }
    
    if (editForm.terminalType !== originalData.value.terminalType) {
      updateData.terminalType = editForm.terminalType
    }

    // 调用API更新客户信息
    const result = await trpc.client.managerUpdate.mutate(updateData)
    
    if (result.success) {
      ElMessage.success('客户信息修改成功')
      router.back()
    } else {
      ElMessage.error(result.message || '修改客户信息失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('修改客户信息失败')
  } finally {
    submitting.value = false
  }
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 生命周期
onMounted(() => {
  loadClientInfo()
})
</script>

<style scoped>
.client-edit-page {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 80px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.back-btn {
  width: 32px;
  height: 32px;
}

.header-placeholder {
  width: 32px;
  height: 32px;
}

.client-info-card {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.client-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
}

.client-basic h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.client-type-info {
  margin: 0;
}

.readonly-info {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.edit-form-card {
  margin: 12px;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.info-notice {
  margin: 12px;
}

.info-notice ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
  font-size: 13px;
}

.info-notice li {
  margin-bottom: 4px;
  line-height: 1.4;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  flex: 1;
  height: 44px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__inner) {
  border-radius: 8px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

:deep(.el-alert__content) {
  font-size: 13px;
}
</style>